#include"TextBox.h"


// 构造函数，初始化成员变量
TextBox::TextBox(int x, int y, int width, int height, int maxWord)
    : x(x), y(y), width(width), height(height), maxWord(maxWord),
    isSelected(false), showCursor(false), cursorPos(0), backspace(false) {}

// 获取文本内容
std::wstring TextBox::getText() {
    return text;
}

// 获取是否被选中的状态
bool TextBox::getSelect() {
    return isSelected;
}

// 判断文本框是否为空
bool TextBox::isEmpty() {
    return text.empty();
}

// 清空文本框内容
void TextBox::clear() {
    text = L"";
    cursorPos = 0;
}

// 设置文本框内容
void TextBox::setText(std::wstring newText) {
    text = newText;
    cursorPos = text.length();
}

// 绘制文本框
void TextBox::draw() {
    setfillcolor(WHITE);
    if (isSelected) {
        setlinecolor(RGB(0, 120, 215));
    }
    else {
        setlinecolor(RGB(122, 122, 122));
    }
    fillrectangle(x, y, x + width, y + height);

    settextcolor(BLACK);
    setbkmode(TRANSPARENT);
    settextstyle(height * 3 / 4, 0, _T("微软雅黑"));

    outtextxy(x + 5, y + (height - textheight(_T("微软雅黑"))) / 2, text.c_str());

    if (isSelected && showCursor) {
        int cursorX = x + 5 + textwidth(text.substr(0, cursorPos).c_str());
        line(cursorX, y + 2 + height / 8, cursorX, y + height * 7 / 8 - 2);
    }
}

// 检查鼠标点击事件
bool TextBox::checkClick(int mouseX, int mouseY) {
    if (mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height) {
        isSelected = true;
        return true;
    }
    isSelected = false;
    cursorPos = text.length();
    return false;
}

// 处理键盘输入事件
void TextBox::keyInput(wchar_t ch) {
    if (isSelected) {
        switch (ch) {
        case '\b':  // 用户按退格键，删掉一个字符
            if (!text.empty() && cursorPos > 0) {
                text.erase(cursorPos - 1, 1);
                cursorPos--;
            }
            break;
        case '\r':
        case '\n':  // 用户按回车键，取消选中状态
            cursorPos = text.length();
            isSelected = false;
            break;
        default:  // 用户按其它键，接受文本输入
            if (backspace) {
                backspace = false;
            }
            else {
                if (text.length() < maxWord) {
                    text.insert(cursorPos, 1, ch);
                    cursorPos++;
                }
            }
            break;
        }
    }
}

// 更新光标状态
void TextBox::updateCursor() {
    static DWORD lastTick = GetTickCount();
    DWORD currentTick = GetTickCount();
    if (currentTick - lastTick >= 500) { // 每500毫秒切换光标状态
        showCursor = !showCursor;
        lastTick = currentTick;
    }
}